import { addEmployee } from "@/api/employeeApi";
import { getAllDepartments } from "@/api/departmentApi";

export default {
    data() {
        return {
            employee: {
                employeeName: "",
                gender: 2, // 默认值为2
                employeePhone: "",
                email: "",
                departmentId: "",
                role: "",
                position: "",
                hireDate: "",
                birthDate: "",
                currentSalaryLevel: "",
                comments: "无", // 默认值
            },
            departments: [], // 存储从 API 获取的部门列表
            rules: {
                employeeName: [
                    { required: true, message: "请输入员工姓名", trigger: "blur" },
                    { min: 2, max: 20, message: "长度需在2-20个字符之间", trigger: ["blur", "change"] }
                ],
                employeePhone: [
                    { required: true, message: "请输入手机号码", trigger: "blur" },
                    {
                        pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
                        message: "请输入正确的手机号格式",
                        trigger: ["blur", "change"]
                    }
                ],
                email: [
                    { required: true, message: "请输入邮箱地址", trigger: "blur" },
                    {
                        type: "email",
                        message: "请输入正确的邮箱格式（如：name@example.com）",
                        trigger: ["blur", "change"]
                    }
                ],
                departmentId: [
                    { required: true, message: "请选择所属部门", trigger: "change" }
                ],
                role: [
                    { required: true, message: "请选择员工角色", trigger: "change" }
                ],
                position: [
                    { required: true, message: "请输入职位名称", trigger: "blur" },
                    { min: 2, max: 30, message: "长度需在2-30个字符之间", trigger: ["blur", "change"] }
                ],
                hireDate: [
                    {
                        required: true,
                        message: "请选择入职日期",
                        trigger: "change"
                    },
                    {
                        validator: (rule, value, callback) => {
                            const today = new Date();
                            today.setHours(0, 0, 0, 0); // 清除时间部分，只比较日期

                            if (!value) {
                                return callback(new Error("请选择入职日期")); // 错误提示与message保持一致
                            }

                            const hireDate = new Date(value);
                            hireDate.setHours(0, 0, 0, 0); // 清除时间部分

                            if (hireDate > today) {
                                return callback(new Error("入职日期不能晚于今日"));
                            }

                            callback();
                        }
                    }
                ],
                birthDate: [
                    {
                        required: true,
                        message: "请选择出生日期",
                        trigger: "change",
                    },
                    {
                        validator: (rule, value, callback) => {
                            const today = new Date();
                            today.setHours(0, 0, 0, 0);

                            if (!value) {
                                return callback(new Error("请选择出生日期"));
                            }

                            const birthDate = new Date(value);
                            birthDate.setHours(0, 0, 0, 0);

                            if (birthDate > today) {
                                return callback(new Error("出生日期不能晚于今日"));
                            }

                            // 合理性校验：出生日期不早于1900年
                            const minDate = new Date("1900-01-01");
                            if (birthDate < minDate) {
                                return callback(new Error("出生日期不应早于1900年"));
                            }

                            callback();
                        }
                    }
                ],
                currentSalaryLevel: [
                    { required: true, message: "请输入薪资级别", trigger: "blur" },
                    {
                        pattern: /^[1-9]\d*$/,
                        message: "请输入正整数",
                        trigger: ["blur", "change"]
                    }
                ]
            }
        };
    },
    async mounted() {
        await this.loadDepartments();
    },
    methods: {
        async loadDepartments() {
            try {
                const result = await getAllDepartments();
                if (result.code === 200) {
                    this.departments = result.data;
                }
            } catch (error) {
                console.error("加载部门数据失败:", error);
                this.$alert("网络错误，请稍后再试", "提示", {
                    confirmButtonText: "确定",
                });
            }
        },
        async onSubmit() {
            if(this.validateEmployee(this.employee.hireDate, this.employee.birthDate))
                return false;
            // 使用 Element UI 的表单验证
            this.$refs.form.validate(async (valid) => {
                if (valid) {
                    try {
                        const result = await addEmployee(
                            this.employee.employeeName,
                            this.employee.gender,
                            this.employee.employeePhone,
                            this.employee.email,
                            this.employee.departmentId,
                            this.employee.role,
                            this.employee.position,
                            this.employee.hireDate,
                            this.employee.birthDate,
                            this.employee.currentSalaryLevel,
                            this.employee.comments
                        );
                        if (result.code === 200) {
                            this.$message.success("添加成功");
                            this.resetForm();
                        } else {
                            this.$message.error(result.message || "添加失败");
                        }
                    } catch (error) {
                        console.error("提交失败:", error);
                        this.$alert("网络错误，请稍后再试", "提示", {
                            confirmButtonText: "确定",
                        });
                    }
                } else {
                    this.$message.error("请填写所有必填字段");
                    return false;
                }
            });
        },
        validateEmployee(hireDate, birthDate) {
            // 计算成年日期（出生日期 + 18年）
            const adultDate = new Date(birthDate);
            adultDate.setFullYear(adultDate.getFullYear() + 18);
            const hireDateOri = new Date(hireDate);
            // 比较入职日期是否满足18年要求
            if (hireDateOri < adultDate) {
                alert("不能招收18岁以下的员工");
                return true;
            }
            return false;
        },
        resetForm() {
            this.$refs.form.resetFields();
            // 重置备注为默认值
            this.employee.comments = "无";
        },
        cancel() {
            this.$router.replace({path: '/employee/AllEmployee'});
        }
    },
};